import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from aws_model.athena_submit import submit
from config import ads
from sql_lambda.delete import delete
from base_class.inspect_logging import print_to_log
import datetime
import json
from aws_model.aws_stepfunc import send_task_success, send_task_failure


def ac_online_iot_fault_code(event):
    date = event.get('p_date')
    if not date:
        beijing = datetime.timezone(datetime.timedelta(hours=7))
        date = datetime.datetime.now(tz=beijing).strftime('%Y-%m-%d-%H')
    filter_date = date[0:10]
    yesterday = (datetime.datetime.strptime(filter_date,'%Y-%m-%d') - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
    delete(ads, f'ac_online_iot_fault_code/p_date={filter_date}')
    table_name = sys._getframe().f_code.co_name
    sql = f'''insert into ads.ac_online_iot_fault_code(
                   select
                        t1.sn,
                        t2.outer_sn as outer_sn,
                        if(t2.model is not null,t2.model,t1.model) as model,
                        t1.fault_code_name as fault,
                        t1.fault_code as fault_code,
                        if(t1.phone is null,t2.phone,t1.phone) as phone,
                        t1.first_report_time as report_time,
                        substr(t1.first_report_time,1,10) as report_date,
                        t1.last_report_time,
                        substr(t1.last_report_time,1,10) as last_report_date,
                        t1.report_minutes,
                        t1.fault_count,
                        t1.current_count,
                        t1.current_sum,
                        if(t2.latest_error_time is not null and t2.latest_error_time !='',true,false) as is_repaired,
                        t2.latest_error_fault_class as last_repire_fault_class,
                        t2.latest_error_fault as last_repire_fault,
                        t2.latest_error_order as last_repair_order,
                        t2.latest_error_time as last_repair_time,
                        '{filter_date}'
                    from
                        (
                            select
                                t1.sn,
                                t2.sn as t2sn,
                                t1.model,
                                t1.fault_code,
                                t1.fault_code_name,
                                t1.phone,
                                if(t2.first_report_time is not null,t2.first_report_time,t1.first_report_time) as first_report_time,
                                if(t1.last_report_time is not null,t1.last_report_time,t2.last_report_time) as last_report_time,
                                t1.report_minutes + if(t2.report_minutes is null,0,t2.report_minutes) as report_minutes,
                                t1.fault_count + if(t2.count is null,0,t2.count) as fault_count,
                                0 as current_count,
                                0 as current_sum
                            from
                            (
                                select
                                    sn,
                                    model,
                                    fault_code,
                                    fault_code_name,
                                    max(phone) as phone,
                                    min(timestamp) as first_report_time,
                                    max(timestamp) as last_report_time,
                                    date_diff('minute',date_parse(min(timestamp),'%Y-%m-%d %H:%i:%S'),date_parse(max(timestamp),'%Y-%m-%d %H:%i:%S')) as report_minutes,
                                    count(1) as fault_count,
                                    count_if(cur is not null) current_count,
                                    sum(if(cur is not null,cur,0)) as current_sum
                                from
                                    (
                                    select
                                        sn,model,timestamp,phone,p_date,cur,
                                        t3.fault_name as fault_code_name,
                                        t3.fault_code
                                    from
                                        (
                                        select
                                            sn,model,timestamp,phone,p_date,currentelectric as cur,
                                            concat(
                                              if(F1Fault = true,'F1,',''),
                                              if(F3Fault = true,'F3,',''),
                                              if(E1Fault = true,'E1,',''),
                                              if(F6Fault = true,'F6,',''),
                                              if(E4Fault = true,'E4,',''),
                                              if(E8Fault = true,'E8,',''),
                                              if(F2Fault = true,'F2,',''),
                                              if(F4Fault = true,'F4,',''),
                                              if(F5Fault = true,'F5,',''),
                                              if(fanCurrentFault = true,'E2,',''),
                                              if(F7Fault = true,'F7,',''),
                                              if(F8Fault = true,'F8,','')
                                            ) as faults
                                        from
                                            ods.iot_ac t
                                        where
                                            p_date = '{filter_date}'
                                            and (F1Fault = true or F3Fault=true or E1Fault=true or F6Fault=true or E4Fault=true or E8Fault=true
                                            or F2Fault=true or F4Fault=true or F5Fault=true or fanCurrentFault=true or F7Fault=true or F8Fault=true)
                                        )t
                                    cross join
                                        unnest(split(faults,',')) as f(fault)
                                    left join
                                        dim.ac_fault_code_mapping t3
                                    on
                                        f.fault = t3.fault_code and t3.level = '1'
                                    where
                                        faults is not null and faults != ''
                                    )t
                                where
                                    fault_code is not null and fault_code != ''
                                group by
                                    sn,model,fault_code_name,fault_code
                            )t1
                            left join
                            (
                                select
                                    *
                                from
                                    dws.ac_iot_fault_continues_td
                                where
                                    p_date = '{yesterday}'
                            )t2
                            on
                            t1.sn = t2.sn and t1.fault_code = t2.fault_code
                        )t1
                    left join
                        dws.ac_all_device_life_td t2
                    on
                        t1.sn = t2.inner_sn and t2.active = '1'
                )
'''
    athena_response = submit(sql)
    print_to_log("athena_response: ", athena_response)
    output = {"msg": f"{table_name} submit ok", "Payload": {}}
    output = json.dumps(output)
    step_response = send_task_success(tasktoken, output)
    print_to_log("step_response: ", step_response)


if __name__ == '__main__':
    try:
        event = json.loads(sys.argv[1])
        tasktoken = event.get('TaskToken')
        ac_online_iot_fault_code(event)
    except Exception as e:
        print_to_log("athena_submit 失败")
        print_to_log("原因： ", str(e))
        send_task_failure(str(e), f'执行{sys._getframe().f_code.co_filename}错误', tasktoken)
